package net.ib.mtalk.ui.setting;

import java.io.File;

import net.ib.mntalk.protocol.Common.UserSetting;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BasePreferenceActivity;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.constant.PrefsConstant;
import net.ib.mtalk.database.helper.BuddyDatabaseHelper;
import net.ib.mtalk.database.helper.InboxDatabaseHelper;
import net.ib.mtalk.database.helper.SuggestionDatabaseHelper;
import net.ib.mtalk.global.GlobalApplication;
import net.ib.mtalk.global.GlobalPreferences;
import net.ib.mtalk.network.NetFlowControl;
import net.ib.mtalk.ui.setting.about.SettingHelp;
import net.ib.mtalk.ui.setting.about.SettingNotice;
import net.ib.mtalk.ui.setting.about.SettingUsageMtalk;
import net.ib.mtalk.ui.setting.display.SettingChatTheme;
import net.ib.mtalk.ui.setting.restore.RestoreActivity;
import net.ib.mtalk.ui.setting.user.UserActivity;
import net.ib.mtalk.ui.start.ClauseActivity;
import net.ib.mtalk.util.MTalkLogWriter;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.preference.RingtonePreference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class SettingsActivity extends BasePreferenceActivity {

	private final static String CLASS = "SettingsActivity : ";
	private Context mContext;
	private Cursor mViewCursor;
	private ProgressDialog mProgressDialog;
	private SettingsController mUiController;
	
	private final int RESET_BUDDY_CONFIRM_DIALOG = 0x00;
	private final int RESET_MSG_CONFIRM_DIALOG = 0x01;
	private final int RESET_AUTH_CONFIRM_DIALOG = 0x02;
	
	private Toast mToast;
	
	private boolean bNoti;
	private boolean bNotiSender;
	private boolean bNotiMsg;
	private boolean bNotiRepeat;
	
	//public static final int HANDLER_REMOVE_MSG = 1;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HandlerMsgConst.HANDLER_REMOVE_VIEW_FAIL:
				Toast.makeText(mContext, "HANDLER_REMOVE_VIEW_FAIL", Toast.LENGTH_SHORT).show();
				mViewCursor.close();
				mProgressDialog.hide();
				break;
			case HandlerMsgConst.HANDLER_REMOVE_VIEW_SUCCESS:
				mViewCursor.close();
				mProgressDialog.hide();
				
				if(msg.arg1 > 0)
				{
					new AlertDialog.Builder(mContext).setMessage(getString(R.string.setting_reset_message_error_msg))
					.setNegativeButton(R.string.ok, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					}).create().show();
				}
				break;
			case HandlerMsgConst.HANDLER_UNREGISTER_USER_SUCCESS:
				NetFlowControl.removeAuthInfo(mContext);
				break;
			case HandlerMsgConst.HANDLER_UNREGISTER_USER_FAIL:
				Toast.makeText(mContext, "HANDLER_UNREGISTER_USER_FAIL", Toast.LENGTH_SHORT).show();
				mProgressDialog.hide();
				break;
			case HandlerMsgConst.HANDLER_UNKNOWN_ERROR:
				Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
				mProgressDialog.hide();
				if(mViewCursor != null && !mViewCursor.isClosed())
					mViewCursor.close();
				break;
			case HandlerMsgConst.HANDLER_GET_BUDDY_INFOS_SUCCESS:
				mProgressDialog.hide();
				Toast.makeText(mContext, "HANDLER_GET_BUDDY_INFOS_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_BUDDY_INFOS_FAIL:
				mProgressDialog.hide();
				Toast.makeText(mContext, "HANDLER_GET_BUDDY_INFOS_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_USER_SETTING_SUCCESS:
				((CheckBoxPreference)findPreference(getString(R.string.preference_noti_title))).setChecked(bNoti);
				((CheckBoxPreference)findPreference(getString(R.string.preference_show_sender_title))).setChecked(bNotiSender);
				((CheckBoxPreference)findPreference(getString(R.string.preference_show_message_title))).setChecked(bNotiMsg);
				((CheckBoxPreference)findPreference(getString(R.string.preference_repeat_noti_title))).setChecked(bNotiRepeat);
				
				setNotiPrefEnabled(bNoti);
				mProgressDialog.hide();
				Toast.makeText(mContext, "HANDLER_SET_USER_SETTING_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_SET_USER_SETTING_FAIL:
				mProgressDialog.hide();
				Toast.makeText(mContext, "HANDLER_SET_USER_SETTING_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_USER_SETTING_SUCCESS:
				mProgressDialog.hide();
				UserSetting userSetting = (UserSetting)msg.obj;
				updateNotiPref(userSetting);
				Toast.makeText(mContext, "HANDLER_GET_USER_SETTING_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_USER_SETTING_FAIL:
				mProgressDialog.hide();
				finish();
				Toast.makeText(mContext, "HANDLER_GET_USER_SETTING_FAIL", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		addPreferencesFromResource(R.xml.preferences);
		mContext = this;
		
		mProgressDialog = new ProgressDialog(mContext);
		mProgressDialog.setMessage(getString(R.string.waiting));
		mProgressDialog.setCancelable(false);
		// 초기화
		aboutInitPreference();
		buddyManagementInitPreference();
		privacyInitPreference();
		notifyInitPreference();
		diplayInitPreference();
		resetInitPreference();
		mUiController = new SettingsController(mContext, mHandler);
		
		PreferenceScreen notiPreferenceScreen = (PreferenceScreen) findPreference("pref_title_notifications");
		notiPreferenceScreen.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				mUiController.getUserSetting();
				mProgressDialog.show();
				return true;
			}
		});
	}

	/**
	 * "엠앤톡 이란?" 설정
	 * About Initialize Preference Items
	 */
	private void aboutInitPreference() {
		// 엠앤톡 사용법
		Preference prefItemUsage = (Preference) findPreference("pref_item_usage");
		prefItemUsage.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				Intent i = new Intent(mContext, SettingUsageMtalk.class);
				startActivity(i);
				return true;
			}
		});
		
		// 공지사항
		Preference prefItemNotice = (Preference) findPreference("pref_item_notice");
		prefItemNotice.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				Intent i = new Intent(mContext, SettingNotice.class);
				startActivity(i);
				return true;
			}
		});
		
		// 도움말
		Preference prefItemHelp = (Preference) findPreference("pref_item_help");
		prefItemHelp.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				Intent i = new Intent(mContext, SettingHelp.class);
				startActivity(i);
				return true;
			}
		});
		
		// 친구에게 소개하기
		Preference prefItemTellAFriend = (Preference) findPreference("pref_item_tell_a_friend");
		prefItemTellAFriend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				String[] itemList = getResources().getStringArray(R.array.entries_pref_tell_a_friend);
				
				new AlertDialog.Builder(mContext)
				.setTitle(R.string.preference_tell_a_priend_dialog_title)
				.setItems(itemList, new OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						switch(which)
						{
						case 0:
							new AlertDialog.Builder(mContext).setMessage(getString(R.string.introduce_sms_alert_msg))
							.setNegativeButton(R.string.ok, new OnClickListener() {
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									
									Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("sms:"));
									sendIntent.addCategory(Intent.CATEGORY_DEFAULT);
									sendIntent.putExtra("sms_body", mContext.getString(R.string.introduce_sms_text));
									startActivity(sendIntent);
								}
							}).create().show();
							break;
						case 1:
							Intent mailIntent = new Intent(Intent.ACTION_SEND);
							mailIntent.putExtra(Intent.EXTRA_SUBJECT, mContext.getString(R.string.introduce_email_title));
							mailIntent.putExtra(Intent.EXTRA_TEXT, mContext.getString(R.string.introduce_email_text));
							mailIntent.setType("message/rfc822");
							startActivity(mailIntent);
							break;
						default:
							break;
						}
					}})
				.setNegativeButton(getString(R.string.cancel), new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
				return true;
			}
		});
		
		// 무엇이든 물어보세요
		Preference prefItemQna = (Preference) findPreference("pref_item_qna");
		prefItemQna.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				String[] itemList = getResources().getStringArray(R.array.entries_pref_qna);
				
				new AlertDialog.Builder(mContext)
				.setTitle(R.string.preference_qna_dialog_title)
				.setItems(itemList, new OnClickListener(){
					public void onClick(DialogInterface dialog, int which) {
						switch(which)
						{
						case 0:
							//TODO : talkbox
							break;
						case 1:
							Intent mailIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:mntalk@infobank.net"));
							//mailIntent.setType("message/rfc822");
							startActivity(mailIntent);
							break;
						default:
							break;
						}
					}})
				.setNegativeButton(getString(R.string.cancel), new OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
				return true;
			}
		});
		
		// 약관 및 개인정보 취급방침
		Preference prefItemTerms = (Preference) findPreference("pref_item_terms");
		prefItemTerms.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			public boolean onPreferenceClick(Preference preference) {
				Intent i = new Intent(mContext, ClauseActivity.class);
				i.putExtra("fromSetting", true);
				startActivity(i);
				return true;
			}
		});
		
		// 버전
		Preference prefVersion = (Preference) findPreference("pref_item_version");
		try {
			prefVersion.setSummary(getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * "대화친구 관리" 설정
	 */
	private void buddyManagementInitPreference() {
		
		// 대화친구 자동 동기화
		CheckBoxPreference prefItemAutoSync = (CheckBoxPreference) findPreference(getString(R.string.preference_auto_sync_title));
		prefItemAutoSync.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				return true;
			}
		});
		
		// 삭제된 대화친구 : 0
		Preference prefItemDeleteFriend = (Preference) findPreference("pref_item_delete_friend");
		prefItemDeleteFriend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				Cursor cursor = BuddyDatabaseHelper.selectRemoveBuddy(mContext);
				if(cursor == null || cursor.getCount() < 1)
				{
					if(mToast==null){
						mToast = Toast.makeText(mContext, R.string.setting_restore_msg1, Toast.LENGTH_LONG);
					}else{
						mToast.cancel();
						mToast.setText(R.string.setting_restore_msg1);
					}
					mToast.show();
				}
				else
				{
					Intent i = new Intent(mContext, RestoreActivity.class);
					i.putExtra(RestoreActivity.KEY_MODE, RestoreActivity.MODE_DELETE_FRIEND);
					startActivity(i);
				}
				
				if(cursor != null)
					cursor.close();
				return true;
			}
		});
		
		// 삭제된 추천친구 : 1
		Preference prefItemDeleteSuggestion = (Preference) findPreference("pref_item_delete_suggestion");
		prefItemDeleteSuggestion.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				Cursor cursor = SuggestionDatabaseHelper.selectDeleteSuggestion(mContext);
				if(cursor == null || cursor.getCount() < 1)
				{
					if(mToast==null){
						mToast = Toast.makeText(mContext, R.string.setting_restore_msg3, Toast.LENGTH_LONG);
					}else{
						mToast.cancel();
						mToast.setText(R.string.setting_restore_msg3);
					}
					mToast.show();
				}
				else
				{
					Intent i = new Intent(mContext, RestoreActivity.class);
					i.putExtra(RestoreActivity.KEY_MODE, RestoreActivity.MODE_DELETE_SUGGESTION);
					startActivity(i);
				}
				
				if(cursor != null)
					cursor.close();
				return true;
			}
		});
		
		// 차단된 대화상대 : 2
		Preference prefItemBlockFriend = (Preference) findPreference("pref_item_block_friend");
		prefItemBlockFriend.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				Cursor cursor = BuddyDatabaseHelper.selectBlockBuddy(mContext);
				if(cursor == null || cursor.getCount() < 1)
				{
					if(mToast==null){
						mToast = Toast.makeText(mContext, R.string.setting_restore_msg2, Toast.LENGTH_LONG);
					}else{
						mToast.cancel();
						mToast.setText(R.string.setting_restore_msg2);
					}
					mToast.show();
				}
				else
				{
					Intent i = new Intent(mContext, RestoreActivity.class);
					i.putExtra(RestoreActivity.KEY_MODE, RestoreActivity.MODE_BLOCK_FRIEND);
					startActivity(i);
				}
				
				if(cursor != null)
					cursor.close();
				return true;
			}
		});
	}
	
	/**
	 * "개인" 설정
	 */
	private void privacyInitPreference(){
		
		// 프로필
		Preference prefItemPrivacy = (Preference) findPreference(getString(R.string.preference_privacy_title));
		prefItemPrivacy.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				Intent i = new Intent(mContext, UserActivity.class);
				startActivity(i);
				return true;
			}
		});
	}
	
	/**
	 * "알림" 설정
	 */
	private void notifyInitPreference(){
		
		// 알림
		CheckBoxPreference prefItemNoti = (CheckBoxPreference) findPreference(getString(R.string.preference_noti_title));
		prefItemNoti.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				if(newValue.toString().equals("false"))
					bNoti = false;
				else
					bNoti = true;
				
				mUiController.setUserSetting(bNoti, bNotiMsg, bNotiSender, bNotiRepeat);
				mProgressDialog.show();
				
				return false;
			}
		});
		
		// 진동
		CheckBoxPreference prefItemVibrate = (CheckBoxPreference) findPreference(getString(R.string.preference_vibrate_title));
		prefItemVibrate.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				return true;
			}
		});
		
		// 알림창에 발신자 표시
		CheckBoxPreference prefItemShowSender = (CheckBoxPreference) findPreference(getString(R.string.preference_show_sender_title));
		prefItemShowSender.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				if(newValue.toString().equals("false"))
					bNotiSender = false;
				else
					bNotiSender = true;
				
				mUiController.setUserSetting(bNoti, bNotiMsg, bNotiSender, bNotiRepeat);
				mProgressDialog.show();
				return false;
			}
		});
		
		// 알림창에 메시지 표시
		CheckBoxPreference prefItemShowMessage = (CheckBoxPreference) findPreference(getString(R.string.preference_show_message_title));
		prefItemShowMessage.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				if(newValue.toString().equals("false"))
					bNotiMsg = false;
				else
					bNotiMsg = true;
				
				mUiController.setUserSetting(bNoti, bNotiMsg, bNotiSender, bNotiRepeat);
				mProgressDialog.show();
				return false;
			}
		});
		
		// 알림 반복
		CheckBoxPreference prefItemRepeatNoti = (CheckBoxPreference) findPreference(getString(R.string.preference_repeat_noti_title));
		prefItemRepeatNoti.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				if(newValue.toString().equals("false"))
					bNotiRepeat = false;
				else
					bNotiRepeat = true;
				
				mUiController.setUserSetting(bNoti, bNotiMsg, bNotiSender, bNotiRepeat);
				mProgressDialog.show();
				return false;
			}
		});
		
		// 알림벨 종류
		RingtonePreference prefItemRingtone = (RingtonePreference) findPreference(getString(R.string.preference_ringtone_title));
		prefItemRingtone.setRingtoneType(RingtoneManager.TYPE_NOTIFICATION);
		prefItemRingtone.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				GlobalPreferences.getSharedPreferences().edit().putString(getString(R.string.preference_ringtone_title), newValue.toString()).commit();
				return true;
			}
		});
	}
	
	private void updateNotiPref(UserSetting userSetting)
	{
		((CheckBoxPreference) findPreference(getString(R.string.preference_noti_title))).setChecked(userSetting.getPushAllowed());
		((CheckBoxPreference) findPreference(getString(R.string.preference_show_sender_title))).setChecked(userSetting.getPushViewBuddy());
		((CheckBoxPreference) findPreference(getString(R.string.preference_show_message_title))).setChecked(userSetting.getPushViewMessage());
		((CheckBoxPreference) findPreference(getString(R.string.preference_repeat_noti_title))).setChecked(userSetting.getPushRepeat());
		
		bNoti = GlobalPreferences.getBooleanNoti(mContext);
		bNotiSender = GlobalPreferences.getBooleanShowSender(mContext);
		bNotiMsg = GlobalPreferences.getBooleanShowMessage(mContext);
		bNotiRepeat = GlobalPreferences.getBooleanRepeatNoti(mContext);
		
		setNotiPrefEnabled(bNoti);
	}
	
	private void setNotiPrefEnabled(boolean enablePush)
	{
		findPreference(getString(R.string.preference_vibrate_title)).setEnabled(enablePush);
		findPreference(getString(R.string.preference_show_sender_title)).setEnabled(enablePush);
		findPreference(getString(R.string.preference_show_message_title)).setEnabled(enablePush);
		findPreference(getString(R.string.preference_repeat_noti_title)).setEnabled(enablePush);
		findPreference(getString(R.string.preference_ringtone_title)).setEnabled(enablePush);
	}
	
	/**
	 * "화면" 설정 
	 */
	private void diplayInitPreference(){
		
		// 대화창 테마 변경
		Preference prefItemDisplayChatTheme = (Preference) findPreference(getString(R.string.preference_display_chat_theme_title));
		prefItemDisplayChatTheme.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				Intent i = new Intent(mContext, SettingChatTheme.class);
				startActivity(i);
				return true;
			}
		});
		
		// 대화창 화면 고정
		CheckBoxPreference prefItemDisplayChatSetting = (CheckBoxPreference) findPreference(getString(R.string.preference_display_chat_setting_title));
		prefItemDisplayChatSetting.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				return true;
			}
		});
	}
	
	/**
	 * "초기화" 설정
	 */
	private void resetInitPreference(){
		
		// 대화친구 및 그룹 초기화
		Preference prefItemResetBuddyGroup = (Preference) findPreference(getString(R.string.setting_reset_buddy_title));
		prefItemResetBuddyGroup.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				showDialog(RESET_BUDDY_CONFIRM_DIALOG);
				return true;
			}
		});
		
		// 메시지함 비우기
		Preference prefItemResetMessage = (Preference) findPreference(getString(R.string.setting_reset_message_title));
		prefItemResetMessage.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				showDialog(RESET_MSG_CONFIRM_DIALOG);
				return true;
			}
		});
		
		// 서비시 인증 해지
		Preference prefItemResetAuthentication = (Preference) findPreference(getString(R.string.setting_reset_authentication_title));
		prefItemResetAuthentication.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				showDialog(RESET_AUTH_CONFIRM_DIALOG);
				return true;
			}
		});
	}
	
	public void onDestroy()
	{
		super.onDestroy();
		clearCache(null);
		if(mProgressDialog != null)
		{
			mProgressDialog.hide();
			mProgressDialog.dismiss();
		}
	}
	
	private void clearCache(File dir)
	{
		if(dir == null)
			dir = getCacheDir();
		
		if(dir == null)
		{
			MTalkLogWriter.i(CLASS + "clearCache() : dir is null");
			return;
		}
		else
			MTalkLogWriter.i(CLASS + "clearCache() : dir = " + dir.toString());
		
		File[] children = dir.listFiles();
		
		for(int i = 0 ; i < children.length ; i++)
		{
			if(children[i].isDirectory())
				clearCache(children[i]);
			else
			{
				children[i].delete();
				MTalkLogWriter.i(CLASS + "clearCache() : deleted file = " + children[i].toString());
			}
		}
	}
	
	protected Dialog onCreateDialog(int id) {	
		Dialog dialog;
		TextView tv = new TextView(this);
		tv.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
		tv.setGravity(Gravity.CENTER_HORIZONTAL);
		switch(id) {
		case RESET_BUDDY_CONFIRM_DIALOG:
			tv.setText(getString(R.string.setting_reset_buddy_confirm_msg));
			dialog = new AlertDialog.Builder(this)
					.setTitle(getString(R.string.setting_reset_buddy_title))
					.setView(tv)
					.setPositiveButton(R.string.yes, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							BuddyDatabaseHelper.removeAllBuddy(mContext);
							mUiController.getAllBuddies();
							removeDialog(RESET_BUDDY_CONFIRM_DIALOG);
							mProgressDialog.show();
						}
					})
					.setNegativeButton(R.string.no, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							removeDialog(RESET_BUDDY_CONFIRM_DIALOG);
						}
					}).create();
			dialog.setOnCancelListener(new OnCancelListener(){
				public void onCancel(DialogInterface dialog) {
					removeDialog(RESET_BUDDY_CONFIRM_DIALOG);
				}});
					return dialog;
		case RESET_MSG_CONFIRM_DIALOG:
			tv.setText(getString(R.string.setting_reset_message_confirm_msg));
			dialog = new AlertDialog.Builder(this)
					.setTitle(getString(R.string.setting_reset_message_title))
					.setView(tv)
					.setPositiveButton(R.string.yes, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
						    mViewCursor = InboxDatabaseHelper.getViewCursor(mContext);
							removeDialog(RESET_MSG_CONFIRM_DIALOG);
							if(mViewCursor == null)
								return;
							else
							{
								mProgressDialog.show();
								//mHandler.sendEmptyMessage(HANDLER_REMOVE_MSG);
								mUiController.removeAllViews(mViewCursor);
							}
						}
					})
					.setNegativeButton(R.string.no, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							removeDialog(RESET_MSG_CONFIRM_DIALOG);
						}
					}).create();
			dialog.setOnCancelListener(new OnCancelListener(){
				public void onCancel(DialogInterface dialog) {
					removeDialog(RESET_MSG_CONFIRM_DIALOG);
				}});
					return dialog;
		case RESET_AUTH_CONFIRM_DIALOG:
			tv.setText(getString(R.string.setting_reset_authentication_confirm_msg));
			dialog = new AlertDialog.Builder(this)
					.setTitle(getString(R.string.setting_reset_authentication_title))
					.setView(tv)
					.setPositiveButton(R.string.yes, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							mUiController.unRegisterUser();
							removeDialog(RESET_AUTH_CONFIRM_DIALOG);
							mProgressDialog.show();
						}
					})
					.setNegativeButton(R.string.no, new OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							removeDialog(RESET_AUTH_CONFIRM_DIALOG);
						}
					}).create();
			dialog.setOnCancelListener(new OnCancelListener(){
				public void onCancel(DialogInterface dialog) {
					removeDialog(RESET_AUTH_CONFIRM_DIALOG);
				}});
					return dialog;
		default:
			break;
		}
		
		return super.onCreateDialog(id);
	}
	
	public static void setDefaultSettingPref()
	{
		String key = GlobalApplication.getContext().getString(R.string.preference_auto_sync_title);
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, true).commit();
		
		key = PrefsConstant.PRF_RECEIVE_LOCK_CHK;
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, false).commit();
		
		key = PrefsConstant.PRF_RECEIVE_CONFIRM_CHK;
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, true).commit();
		
		key = GlobalApplication.getContext().getString(R.string.preference_noti_title);
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, true).commit();

		key = GlobalApplication.getContext().getString(R.string.preference_vibrate_title);
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, true).commit();
		
		key = GlobalApplication.getContext().getString(R.string.preference_show_sender_title);
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, true).commit();
		
		key = GlobalApplication.getContext().getString(R.string.preference_show_message_title);
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, true).commit();
		
		key = GlobalApplication.getContext().getString(R.string.preference_repeat_noti_title);
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, true).commit();
		
		key = GlobalApplication.getContext().getString(R.string.preference_display_chat_setting_title);
		if(!GlobalPreferences.getSharedPreferences().contains(key))
			GlobalPreferences.getSharedPreferences().edit().putBoolean(key, false).commit();
	}
}
